package com.uni.controller.admin;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.uni.base.RestResponse;
import com.uni.pojo.Role;
import com.uni.pojo.User;
import com.uni.service.RoleService;
import com.uni.service.UserService;
import com.uni.utils.PageUtil;
import com.uni.utils.ParamUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin/role")
public class RoleAdminController {
    @Autowired
    UserService userService;
    @Autowired
    RoleService roleService;


    @PostMapping("/query")
    public String getRoleInfo(@RequestBody(required = false) Map<String, String> paramMap) {
        ParamUtil.translate(paramMap);
        int pageNum = Integer.parseInt(paramMap.getOrDefault("pageNow", "1"));
        PageHelper.startPage(pageNum, 3);
        List<User> users = userService.getUserRoleByMapPojos(paramMap);
        List<Role> roles = roleService.queryAllRole();
        PageInfo pageInfo = PageUtil.setPageInfo(pageNum, 3, users);
        return RestResponse.ok(new HashMap<String, Object>(){{
            put("pageInfo", pageInfo);
            put("roleInfo", roles);
        }}).toJSONString();
    }

    @PostMapping("/update")
    public String upRoleByID(@RequestBody Map<String, Object> map){
        List<String> usersCode = (List<String>) map.getOrDefault("users", null);
        String type = (String) map.get("type");
        if(usersCode == null || usersCode.isEmpty()) return RestResponse.fail("所查询到的用户为空").toJSONString();
        int i = 0;
        int maxLevel = roleService.queryAllRole().size() + 1;

        for (String userCode : usersCode) {
            // 获取当前用户的角色
            User user = new User() {{
                setCode(userCode);
            }};
            Role role = roleService.queryRoleByUserCode(user);
            Role newRole = null;
            if(type.equals("up"))                   // 升级角色
                newRole = roleService.queryById(Math.min(role.getId() + 1, maxLevel));
            else if(type.equals("down"))            // 降级
                newRole = roleService.queryById(Math.max(role.getId() - 1, 1));

            i = (roleService.updateRoleByCode(user, newRole) != null) ? i + 1 : i;
        }
        return i == usersCode.size() ?
                RestResponse.ok("操作成功!").toJSONString()
                    : RestResponse.fail("操作失败.").toJSONString();
    }
    @PostMapping("/queryall")
    public String getRoleInfo() {
        List<Role> roles = roleService.queryAllRole();
        return roles.isEmpty() ? RestResponse.fail("查询到的用户信息为空").toJSONString()
                    : RestResponse.ok(roles).toJSONString();
    }

}
